﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Web;

namespace WebService.Nafania.ViewLayer.Model
{
	[DataContract]
	public class KeyValuePair
	{
		[DataMember]
		public string Key { get; set; }
		[DataMember]
		public object Value { get; set; }
	}

	public static class KeyValuePairExtention
	{
		public static KeyValuePair GetByKey(this KeyValuePair[] array, string key)
		{
			if (key == null)
				throw new ApplicationException("Key is null");

			return array.SingleOrDefault(x => x.Key == key);
		}

		public static List<KeyValuePair> GetByBeginOfKey(this KeyValuePair[] array, string key)
		{
			if (key == null)
				throw new ApplicationException("Key is null");

			return array.Where(x => x.Key.StartsWith(key)).ToList();
		}

		public static object GetValueByKey(this KeyValuePair[] array, string key)
		{
			var pair = array.GetByKey(key);
			if (pair == null)
				throw new ApplicationException("Key: '" + key + "' didn't find");

			return pair.Value;
		}

		public static object GetNotNullValue(this KeyValuePair[] array, string key)
		{
			var value = array.GetValueByKey(key);
			if (value != null)
				return value;

			throw new ApplicationException("Value is null");
		}

		public static string GetStringValueByKey(this KeyValuePair[] array, string key)
		{
			var value = array.GetNotNullValue(key);
			if (value is string)
				return (string)value;

			throw new NotImplementedException();
		}

		public static Guid GetGuidValueByKey(this KeyValuePair[] array, string key)
		{
			var value = array.GetNotNullValue(key);
			if (value is Guid)
				return (Guid)value;

			return Guid.Parse(value.ToString());
		}

		public static int GetIntValueByKey(this KeyValuePair[] array, string key)
		{
			var value = array.GetNotNullValue(key);
			if (value is int)
				return (int)value;

			return int.Parse(value.ToString());
		}

		public static List<string> GetListStringValueByBeginOfKey(this KeyValuePair[] array, string key)
		{
			var pairsList = array.GetByBeginOfKey(key);

			return pairsList.OrderBy(x => x.Key).Select(x => x.Value).Cast<string>().Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x).ToList();
		}
	}
}